package com.chen.pfm.utils;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.data.dataability.DataAbilityPredicates;

import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;



public class DataBaseUtil {
    static final HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP, 0x2022001, "DataBaseUtil");
   static String strUri = "dataability:///com.chen.pfm.BaseInfoDataAbility/baseinfo";
    public static String GetValue( Context context,String key) {
        String vaule = null;
        //访问本地数据库，看用户是否存在，如果存在则不需要登录，直接跳转到首页
        DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(context);
        Uri uri = Uri.parse(strUri);
        //查询的条件封装
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        //在数据库里，找key的数据
        predicates.equalTo("key", key);
        String[] colums = {"value"};

        try {
            //数据库帮助类调用查询，得到结果集
            ResultSet rs = dataAbilityHelper.query(uri, colums, predicates);
            //如果结果集合不为空
            if (rs.getRowCount() > 0) {
                //结果指针移到第一行
                rs.goToFirstRow();
                vaule = rs.getString(0);
            }
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        return vaule;
    }

    //保存网络的数据，存储到指定的uri数据库中
    public static int saveValue(Context context, String key, String value) {
        int insert = -1;//成功为1，失败为-1
        ValuesBucket valuesBucket = new ValuesBucket();
        valuesBucket.putString("key", key);
        valuesBucket.putString("value", value);
        Uri uri = Uri.parse(strUri);
        //访问本地数据库
        DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(context);
        try {
            insert = dataAbilityHelper.insert(uri, valuesBucket);

        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();

        }
        return insert;
    }

    //删除指定数据
    public static int deleteValue(Context context, String key) {
        int del = -1;//成功为1，失败为-1
        Uri uri = Uri.parse(strUri);
        //查询的条件封装
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.equalTo("key", key);
        //访问本地数据库
        DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(context);
        try {
            del = dataAbilityHelper.delete(uri, predicates);

        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        return del;
    }


}
